package indi.zn.commons.serialno;

import java.util.Map;

import indi.zn.script.groovy.GroovyRunner;

public class GroovyExecutor implements SerialExecutor{
	
	 private GroovyRunner gyRunner;
	 
	 private String script;
	 
	 private ScriptPrinter printer;
	 
	 private String[] imports;
	 
	 private String snName;
	 
	 
	 private static final String importBase="import java.util.*\r\n"
			 	+"import org.zn.commons.collection.* \r\n"
			 	+"import org.zn.commons.serialno.ScriptPrinter \r\n"; 
	 
	 private static final String classBase=	"class Printer";
	 private static final String top="  implements ScriptPrinter{\r\n" + 
	 		"	\r\n" + 
	 		"	def Map<String, Object> base;\r\n" + 
	 		"	\r\n" + 
	 		"	def setContext(base) {\r\n" + 
	 		"		this.base=base\r\n" + 
	 		"	}\r\n" + 
	 		"	\r\n" + 
	 		"	\r\n" + 
	 		"\r\n" + 
	 		"	@Override\r\n" + 
	 		"	public String print(Map<String, Object> ctx) {";
	 
	 
	 private static final String foot="}}";
	 
	
	 
	 public GroovyExecutor() {
		// TODO Auto-generated constructor stub
	}
	 
	 public GroovyExecutor(String snName,GroovyRunner gyRunner,String script) {
		 this.snName=snName;
			this.script=script;
			this.gyRunner=gyRunner;
			
			this.intScriptClass();
		}
	 
	 
	 public GroovyRunner getGyRunner() {
		return gyRunner;
	}

	public void setGyRunner(GroovyRunner gyRunner) {
		this.gyRunner = gyRunner;
	}

	public String getScript() {
		return script;
	}

	public void setScript(String script) {
		this.script = script;
	}
	public String[] getImports() {
		return imports;
	}

	public void setImports(String[] imports) {
		this.imports = imports;
	}
	
	

	@SuppressWarnings("unchecked")
	public void intScriptClass() {
		
	scriptBinding();
		
	Class<ScriptPrinter> clazz=(Class<ScriptPrinter>) gyRunner.parseGroovyClass(script);
		
	try {
		printer=clazz.newInstance();
	} catch (InstantiationException | IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
	
	
	private void scriptBinding() {
		
		String imp=importBase;
		
		if(imports!=null) {
		for (String im : imports) {
			imp+= im+"\r\n";
		}
		}
		
		script= imp+classBase+snName+top+script+foot;
		
	}


	/**
	 *  script 需要为 上下文中的 result变量赋值 
	 */
	@Override
	public String  execute(Map<String, Object> context) {
			
		return 	printer.print(context);
				
	}



	@Override
	public SerialNo executeS(Map<String, Object> context) {
		// TODO Auto-generated method stub
		return null;
	}
	
	 
}
